package uia.alumni.web;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uia.alumni.data.User;



/**
 * Log in a user. Displays the Home page.
 * 
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class Login extends Command {

    public static final String SERVLET_NAME = "login";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;


    public Login() {
        super(null);
    }

    
    /**
     * Log in the user. Retrieve the user object from the database,
     * and store it in the session.
     *
     * @param request DOCUMENT ME!!
     * @throws IOException DOCUMENT WHEN!!
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter(USERNAME);
        String password = request.getParameter(PASSWORD);

        EntityManager em = emf.createEntityManager();
        Query q = em.createNamedQuery("User.findByName");
        q.setParameter("name", userName);
        User user = (User)q.getSingleResult();

        // check the password
        if (user != null
                && password != null
                && !password.equals(user.getPassword()))
            user = null;
        em.close();

        // if user is not null we have a valid login
        if (user == null) {
            addMessage(request, "Wrong username, password or both!");
            log("Login failed for '"+userName+"/"+password+"'");
        }
        else {
            request.getSession(true).setAttribute(USER, user);
            log(user+" logged in");
        }
        forwardTo(Home.SERVLET_NAME, request, response);

    }


    public final static long serialVersionUID = 1;

}
